/**
 * Copyright 2006-2015 handu.com
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.iepacj.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author amssy
 * @version V1.0
 * @description TODO
 * @date 2016/8/27
 */

public class ClientTest {

    public static void main(String[] args) throws IOException {

        connectToServer();

    }

    private static void connectToServer() throws IOException {

        String host = "192.168.53.9";
        int port = 6666;

        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress(host, port));

        System.out.println("连接到服务器");

        ByteBuffer dst = ByteBuffer.allocate(1024 * 6);

        System.out.println("等待服务器响应");

        sc.read(dst);

        System.out.println("服务器返回");

        System.out.println(dst);

        dst.flip();

        System.out.println("flip后: " + dst + "; " + dst.remaining());

        ByteBuffer buf = ByteBuffer.allocate(dst.limit());

        while (dst.hasRemaining()) {
            byte b = dst.get();
            if (b == 13) {
                System.out.println("到最后了: " + b);
                break;
            }
            buf.put(b);
        }
        buf.flip();
        System.out.println("buf flip: " + buf);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.limit(); i++) {
            sb.append(buf.get(i)).append(" ");
        }

        System.out.println(sb.toString());

        byte[] b = new byte[buf.limit()];
        buf.get(b);

        System.out.println("读到的响应: " + new String(b));

        System.out.println("完成退出");

    }

}
